package com.strongdigit.spweb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/girl")
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    /**
     * 查询所有姑娘
     *
     * @return
     */
    @GetMapping(value = "/girls")
    public List<Girl> girlList() {

        return girlRepository.findAll();
    }

    /**
     * 新增一个姑娘
     *
     * @param size
     * @param age
     * @return
     */
    @PostMapping("/add")
    public Girl add(@RequestParam(value = "cupSize", defaultValue = "C") String size,
                    @RequestParam(value = "age", defaultValue = "18") Integer age) {

        Girl girl = new Girl();
        girl.setAge(age);
        girl.setCupSize(size);
        return girlRepository.save(girl);

    }

    /**
     * 根据ID获取一个姑娘
     *
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Girl GetGirlById(@PathVariable(value = "id", required = true) Integer id) {

        return girlRepository.getOne(id);
       // girlRepository.getOne(id);
        //这里在new一个girl对象是因为Hibernate 懒加载的问题导致，Hibernate直接获取pojo的对象内存在Lazy关联对象，执行json
        //转换是，才从db中加载对象，但是此时session已关闭，导致加载失败，从而json转换失败

//        Girl girl2 = new Girl();
//        girl2.setId(girl.getId());
//        girl2.setName(girl.getName());
//        girl2.setAge(girl.getAge());
//        girl2.setCupSize(girl.getCupSize());
        //return girl2;

    }

    /**
     * 删除一个姑娘
     *
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public Boolean DeleteById(@PathVariable(value = "id", required = true) Integer id) {
        girlRepository.deleteById(id);
        return true;

    }

    /**
     * 更新一个妞
     *
     * @param id
     * @param name
     * @param size
     * @param age
     * @return
     */
    @Transactional
    @PutMapping("/update/{id}")
    public Girl Update(@PathVariable(value = "id", required = true) Integer id,
                       @RequestParam(value = "name") String name,
                       @RequestParam(value = "size") String size,
                       @RequestParam(value = "age") Integer age
    ) {
        Girl girl = girlRepository.getOne(id);

        girl.setName(name);
        girl.setCupSize(size);
        girl.setAge(age);
        return girlRepository.save(girl);

    }



    /**
     * 查询所有姑娘
     *
     * @return
     */
    @GetMapping(value = "/girls/age/{age}")
    public List<Girl> girlListByAge(@PathVariable(value = "age") Integer age) {

        return girlRepository.findByAge(age);
    }

}
